<!-- 从业者端-在线学习-题库列表-题库练习-->
<template>
	<view class="container">
		<!-- 题目头部 -->
		<view class="question-header">
			<view class="question-type">{{getQuestionType(currentQuestion.type)}}</view>
			<!-- 倒计时 -->
			<view class="timer">
				<u-icon name="clock" color="#FF4D4F" size="32"></u-icon>
				<text>{{ formattedTime }}</text>
				<text @click="progressSub" style="font-size: 32rpx; margin-left: 10px;">交卷</text>
			</view>
		</view>

		<!-- 题目内容 -->
		<view class="question-content">
			{{currentQuestion.content}}
		</view>

		<!-- 选项内容区 -->
		<!-- 单选和多选项显示 -->
		<view class="options-list">
			<view v-if="currentQuestion.type === '0' || currentQuestion.type === '1'">
				<view v-for="(option, index) in currentQuestion.options" :key="index" class="option-item" :class="{
					'selected': selectedAnswers.includes(index),
				}" @click="selectOption(index)">
					{{String.fromCharCode(65 + index)}}. {{option}}
				</view>
			</view>

			<!-- 判断题选项 -->
			<view v-if="currentQuestion.type === '2'" class="judge-options">
				<view class="judge-option" :class="{
					'selected': selectedAnswers.includes(0),
				}" @click="selectOption(0)">
					正确
				</view>
				<view class="judge-option" :class="{
					'selected': selectedAnswers.includes(1),
				}" @click="selectOption(1)">
					错误
				</view>
			</view>

			<!-- 简答题输入框 -->
			<view v-if="currentQuestion.type === '3'" class="answer-input">
				<u-input v-model="answerText" type="textarea" placeholder="请输入您的答案" height="200"></u-input>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="action-bar">
			<view class="action-btn prev-btn" @click="prevQuestion">上一题</view>
			<view class="action-center" @click="showCateWin">
				<view class="action-order">
					<u-icon name="order" color="#03B8CD" size="32"></u-icon>
				</view>
				<view class="action-btn catalog-btn">
					{{ currentIndex+1 }}/{{ questions.length }}
				</view>
			</view>
			<view class="action-btn  next-btn"   @click="nextOrConfirm"  v-if="currentIndex+1 < questions.length">
				{{  currentQuestion.type != '1' ? '下一题' : '确定' }}
			</view>
			<view class="action-btn next-btn" :class="{ disabled: !currentIndex}" @click="submitPaper"  v-else>
				{{ lastBut }}
			</view>
		</view>

		<!-- 目录弹窗 -->
		<u-popup v-model="showCatalog" mode="bottom" height="60%">
			<view class="catalog-popup">
				<view class="popup-header">
					<text class="popup-title">题目目录</text>
					<u-icon name="close" @click="showCatalog = false"></u-icon>
				</view>
				<view class="question-list">
					<view class="question-item" v-for="(item, index) in answeredQuestions" :key="index"
						:class="{ 'active': currentQuestion === item,
						          'selected': answeredQuestions[index].isDo === 1,
										 // 'correct': answeredQuestions[index].duicuo === 0,
										 // 'wrong':answeredQuestions[index].duicuo === 1,
						 }" @click="jumpToQuestion(item,index)">
						<text>{{ item.id }}</text>
						<u-icon :name="item.isCorrect ? 'checkmark-circle' : 'close-circle'"
							:color="item.isCorrect ? '#CEF1BF' : '#FDD9DB'" size="16"></u-icon>
					</view>
				</view>
			</view>
		</u-popup>
		
		<!-- 交卷确认弹窗，若时间到，直接交卷，若时间未到，则有继续答题按钮 -->
		<u-modal v-if="timeLeft != 0" v-model="showSubmitModal" title="时间到" content="考试时间已结束，系统将自动交卷" show-cancel-button
			confirm-text="立即交卷" cancel-text="继续答题" @confirm="submitExam" @cancel="continueExam"></u-modal>
		<u-modal v-else v-model="showSubmitModal" title="时间到" content="考试时间已结束，系统将自动交卷" :show-cancel-button="false"
			confirm-text="立即交卷" @confirm="submitExam"></u-modal>		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 倒计时
				showSubmitModal: false,
				timeLeft: 30 * 60, // 30分钟，单位秒
				// timeLeft: 3,
				timer: null,
				showAnswer: false, // 是否显示答案
				showCatalog: false,
				answerText: '', // 简答题答案
				lastBut:'交卷', ///最后按钮的处理
				// 0-单选题；1-多选题；2-判断题；3-简答题； 
				btkCode: '', ///接收传过来的考题的code
				btTaskCode: '', ////任务code
				saveBtm: [], ///存储接收到的题目内容
				questions: [],
				doQuestionAnswer:[], ////做答时需要获取题目列表，跟question一一对应，存储答案时使用此数组的cyctkd_code
				selectedAnswers: [], // 用户选择的答案索引编号
				saveAnswers:[], ///用户选择的答案
				
				answeredQuestions: [],  ////历史已答题项index
				currentIndex: 0,  ////当前项的index
				
				tmpSaveSelect: [], ////临时存储单选和多选的四个选择项
				tmpSaveAnswer:[], ////临时存储所有类型题目的答案
				isExce: 'kaoshi' ///是否练习
			}
		},
		computed: {
			// 当前题目
			currentQuestion() {
				return this.questions[this.currentIndex];
			},
			// 格式化倒计时显示
			formattedTime() {
				const minutes = Math.floor(this.timeLeft / 60)
				const seconds = this.timeLeft % 60
				return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
			}
		},
		mounted() {
			// 开始倒计时
			this.startTimer()
		},
		beforeDestroy() {
			// 清除计时器
			this.clearTimer()
		},
		onLoad(options) {
			this.timeLeft = options.kstime*60
		},
		onShow() {
			// this.getBtmDetails()
			// 创建练习或考试,任务开始，并返回当前题库具体题目
			this.createMnKsTask()
		},
		// 页面卸载（关闭或路由跳转）时
		onUnload() {
			// 任务结束
			this.voerTask()
		},
		methods: {			
			// 题目类型的变化
			getQuestionType(type) {
				switch (type) {
					case '0':
						return '单选题';
					case '1':
						return '多选题';
					case '2':
						return '判断题';
					case '3':
						return '简答题';
					default:
						return '';
				}
			},
			// 任务结束
			voerTask() {
				this.$u.api.finishtkbytaskcode({
					"cyctkcode": this.btTaskCode, ////#课程题库学习的任务code
				}).then(res => {
					console.log('任务结束：', res)					
				})
			},
			
			// 创建练习或考试任务
			createMnKsTask() {
				this.$u.api.createtktask({
					"btkcode": "",//#题库编号
					"usercode": uni.getStorageSync('usercode'),//#从业者用户code
					"tytype":"1", ///#题库练习类型，0练习，1模拟考试，2竞赛，模拟考试和竞赛时不需要传入题库编号，从用户的题库中进行抽取
				}).then(res => {	
					this.btTaskCode = res.data.base_info.cyctkcode
					let tminfo = res.data.base_info.tminfo
					this.saveBtm = []
					for(var i=0; i<tminfo.length; i++) {
						this.saveBtm.push(tminfo[i])
					}
					console.log('练习考试：', res,this.saveBtm)
					// 考试题目转化
					this.tmApiToLocal()
					// 加载所有题目编号
					this.downAlltm()
					// 加载复制的题目，主要用于存储答案
					this.getBtmDetails()
				})				
			},	
					
			// 加载所有题目
			downAlltm() {
				this.answeredQuestions = []
				for (let i = 0; i < this.questions.length; i++) {
					// isDo=0未做，1已做，duicou=0错，1对，9未选择默认
					this.answeredQuestions.push({
						id: i+1,
						isDo: 0
					})
				}
				console.log('加载所有题目编号：', this.answeredQuestions)
			},
			
			// 查询题库下题目
			getBtmDetails() {
				this.$u.api.querytktmlist({
					"cyctkcode": this.btTaskCode,
				}).then(res => {
					this.doQuestionAnswer = res.data.base_info
					console.log('复制：', res, this.doQuestionAnswer)
				})
			},
			// 进行题目格式转换,最终存储到questions
			// // 0-单选题；1-多选题；2-判断题；3-简答题；
			tmApiToLocal() {
				this.questions = []				
				for(let i=0; i < this.saveBtm.length; i++) {
					this.tmpSaveSelect = []
					this.tmpSaveAnswer = []							
					
					// 为单选和多选时
					if(String(this.saveBtm[i].tminfo.baseinfo.btktm_type) == '0' || String(this.saveBtm[i].tminfo.baseinfo.btktm_type) == '1') {
						// 转换选项						
						for(let j=0; j<this.saveBtm[i].tminfo.items.length; j++) {							
							this.tmpSaveSelect.push(this.saveBtm[i].tminfo.items[j].btktmi_name);		
							// 存储答案
							for(let k=0; k<this.saveBtm[i].tminfo.answers.length; k++) {								
								if(this.saveBtm[i].tminfo.answers[k].btktma_name == this.saveBtm[i].tminfo.items[j].btktmi_name) {
									this.tmpSaveAnswer.push(j);
								}
							}
						}
						this.questions.push({
							cyctktdcode: this.saveBtm[i].cyctkd_code,
							id: this.saveBtm[i].tminfo.baseinfo.btk_code,
							type: String(this.saveBtm[i].tminfo.baseinfo.btktm_type),
							content: this.saveBtm[i].tminfo.baseinfo.btktm_name,
							options: this.tmpSaveSelect,
							answer: this.tmpSaveAnswer, // 正确答案索引
							analysis: this.saveBtm[i].tminfo.baseinfo.btktm_answerdesc,
							isFavorite: false
						})	
						console.log('转换后-0：', this.questions)
					} else if(String(this.saveBtm[i].tminfo.baseinfo.btktm_type) === '2'){
						 if(this.saveBtm[i].tminfo.answers[0].btktma_name === '正确') {
							 this.tmpSaveAnswer.push(0);
						 } else {
							 this.tmpSaveAnswer.push(1);
						 }	
						this.questions.push({
							cyctktdcode: this.saveBtm[i].cyctkd_code,
							id: this.saveBtm[i].tminfo.baseinfo.btk_code,
							type: String(this.saveBtm[i].tminfo.baseinfo.btktm_type),
							content: this.saveBtm[i].tminfo.baseinfo.btktm_name,
							options: ['正确', '错误'],
							answer: this.tmpSaveAnswer, // 正确答案索引
							analysis: this.saveBtm[i].tminfo.baseinfo.btktm_answerdesc,
							isFavorite: false
						})	
					} else if(String(this.saveBtm[i].tminfo.baseinfo.btktm_type) === '3') {
						this.questions.push({
							cyctktdcode: this.saveBtm[i].cyctkd_code,
							id: this.saveBtm[i].tminfo.baseinfo.btk_code,
							type: String(this.saveBtm[i].tminfo.baseinfo.btktm_type),
							content: this.saveBtm[i].tminfo.baseinfo.btktm_name,
							options: '',
							answer: this.saveBtm[i].tminfo.answers[0].btktma_name, // 正确答案索引
							analysis: '',
							isFavorite: false
						})	
					}
					
				}
				console.log('转换后：', this.questions)
				
			},			
			
			// 开始倒计时
			startTimer() {
				this.clearTimer()
				this.timer = setInterval(() => {
					if (this.timeLeft > 0) {
						this.timeLeft--
					} else {
						this.timeUp()
					}
				}, 1000)
			},
			
			// 清除计时器
			clearTimer() {
				if (this.timer) {
					clearInterval(this.timer)
					this.timer = null
				}
			},
			
			// 时间到处理
			timeUp() {
				this.clearTimer()
				this.showSubmitModal = true
			},
			
			
			// 记录已答题目
			// recordAnswered() {
			// 	// console.log('已选答案-1：', this.answeredQuestions)
			// 	  // duicou=0 表示正确，否则表示错误，9表示未选择
			// 	  if (!this.answeredQuestions.includes(this.currentIndex)) {
			// 			  // 判断 selectedAnswers 的所有元素是否都包含在 answer 中
			// 			  const isFullyContained = this.selectedAnswers.every(item => 
			// 			    this.currentQuestion.answer.includes(item));
			// 			if(isFullyContained) {
			// 				this.answeredQuestions[this.currentIndex].duicuo = 0 ;
			// 			} else {
			// 				this.answeredQuestions[this.currentIndex].duicuo = 1 ;
			// 			}
						 
			// 	  }
			// 	console.log('已选答案-1：', this.answeredQuestions,this.selectedAnswers,this.currentQuestion)
			// },
			
			
			// 做题过程中交卷
			progressSub() {
				this.showSubmitModal = true
			},
			
			// 提交试卷
			submitExam() {
				uni.showLoading({
					title: '正在交卷...'
				})
				// 模拟交卷请求
				setTimeout(() => {
					uni.hideLoading()
					// 交卷保存当前题目
					this.saveDoQuestion()
					uni.showToast({
						title: '交卷成功',
						icon: 'success'
					})
					// 跳转到成绩页面
					uni.redirectTo({
						url: '/pages/Practitioner/question/simulationResult'
					})
				}, 1500)
			},
			
			// 继续答题
			continueExam() {
				// 额外增加5分钟
				// this.timeLeft = 5 * 60
				this.startTimer()
				this.showSubmitModal = false
			},
			
			
			
			
			// 切换收藏状态
			toggleFavorite() {
				this.currentQuestion.isFavorite = !this.currentQuestion.isFavorite;
				uni.showToast({
					title: this.currentQuestion.isFavorite ? '已收藏' : '已取消收藏',
					icon: 'none'
				});
				// 实际项目中这里应该调用API保存收藏状态
			},

			// 选择选项
			selectOption(index) {
				if (this.currentQuestion.type === '0') {
					// 单选题只能选一个
					this.selectedAnswers = [index];
					// this.saveAnswers = [String.fromCharCode(65 + index)]
					this.saveAnswers = [this.currentQuestion.options[index]]
					// this.showAnswer = true;
				} else if (this.currentQuestion.type === '2'){
					// 判断题只能选一个
					this.selectedAnswers = [index];
					this.saveAnswers = [index == '0'? '正确': '错误']
					// this.showAnswer = true;					
				}else if (this.currentQuestion.type === '1') {
					// 多选题可以多选
					const idx = this.selectedAnswers.indexOf(index);
					if (idx === -1) {
						// 未选过，就变成选择的颜色
						this.selectedAnswers.push(index);
						// this.saveAnswers.push(String.fromCharCode(65 + index))
						this.saveAnswers.push(this.currentQuestion.options[index])
					} else {
						// 已选过再点，就取消
						this.selectedAnswers.splice(idx, 1);
						this.saveAnswers.splice(idx, 1);
					}
				}
			},

   // 记录已做题
    recordAnswered() {
      if (!this.answeredQuestions.includes(this.currentIndex)) {
        this.answeredQuestions.push(this.currentIndex);
				this.answeredQuestions[this.currentIndex].isDo = 1
				console.log('已选答案-1：', this.answeredQuestions)
      }
    },


			// 上一题
			prevQuestion() {
				if (this.currentIndex > 0) {
					this.currentIndex--;
					this.resetQuestion();
					// 这里应该加载上一题的数据
					// 从服务器调取跳转题目的答案
					this.getJumpToAnswer()
				} else {
					uni.showToast({
						title: '已经是第一题了',
						icon: 'none'
					});
				}
			},

			// 下一题或确认
			nextOrConfirm() {
				// console.log('next:', this.currentIndex)
				this.goToNextQuestion();
				// if (this.showAnswer) {
					
				// } else {
				// 	this.showAnswer = true;
				// }
			},

			// 跳转到下一题
			goToNextQuestion() {
				console.log('点下一步时：', this.currentQuestion)
				// 模拟考试保存做题目至服务器
				this.saveDoQuestion()
				// 记录已做题
				this.recordAnswered();
				// 进入下一题
				if (this.currentIndex < this.questions.length - 1) {
					this.currentIndex++;
					// 新题目重置
					this.resetQuestion();
					// 这里应该加载下一题的数据
				} else {
					uni.showToast({
						title: '已经是最后一题',
						icon: 'none'
					});
					this.lastBut = '交卷'
				}
			},
			
			// 模拟考试保存做题目至服务器
			saveDoQuestion() {
				console.log('当前题目code:', this.questions[this.currentIndex],this.saveAnswers)
				let currentTMcode = this.doQuestionAnswer[this.currentIndex].cyctkd_code
				if(this.questions[this.currentIndex].type === '3') {
					this.saveAnswers.push(this.answerText)
				} 				
				this.$u.api.savetktm({
					"cyctktdcode": currentTMcode,  ///#题库任务题目code
					"answers":this.saveAnswers   ////#答案
				}).then(res => {
					console.log('保存题目：',res)
				})			
			},

			// 重置题目状态
			resetQuestion() {
				this.selectedAnswers = [];
				this.saveAnswers = [];			
				this.answerText = '';
			},
			
			// 显示目录弹窗
			showCateWin() {
				this.showCatalog = true
			},

			// 跳转到指定题目
			jumpToQuestion(item,index) {
				// this.currentQuestion = number;
				this.currentIndex = item.id-1;
				this.resetQuestion();
				// 从服务器调取跳转题目的答案
				this.getJumpToAnswer()
				this.showCatalog = false;
				// 这里应该加载指定题目的数据
			},
			
			// 从服务器调取跳转题目的答案
			getJumpToAnswer() {
				// 跳转到相应题目前，需要从服务端获取回所有已经做过题目的答案
				// this.getBtmDetails()
				console.log('跳转的Index-1:',this.doQuestionAnswer,this.currentIndex)
				let cyctkdcode = this.doQuestionAnswer[this.currentIndex].cyctkd_code
				this.$u.api.querytktm({
					"cyctkdcode": cyctkdcode
				}).then(res => {
					console.log('跳转的Index:',res)
					this.jumpAnswer(res.data.base_info)
				}).catch(err =>{
					
				})
			},
			// 跳转后进行答案匹配
			jumpAnswer(baseinfo) {
				let currentjumpTm = this.questions[this.currentIndex]						
				for(let i=0; i < baseinfo.cyctkd_answer.length; i++) {
					for(let j=0; j < currentjumpTm.options.length; j++) {
						if(currentjumpTm.options[j] == baseinfo.cyctkd_answer[i]) {
							this.selectedAnswers.push(j)
						}
					}
				}			
				console.log('跳转后选择的答案：',this.selectedAnswers)

			},
			// 交卷
			submitPaper() {
				this.saveDoQuestion()
				// 任务结束
				this.voerTask()
				// 跳转
				uni.navigateTo({
				  url: `/pages/Practitioner/question/simulationResult?isExce=${this.isExce}&btTaskCode=${this.btTaskCode}`
				})
			}

		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
		padding-bottom: 120rpx;
		background-color: #F1F7F7;
		min-height: 100vh;
	}

	// 题目头部
	.question-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		margin-top: 100rpx;
		border-bottom: 1px solid #d5dada;

		.question-type {
			font-size: 34rpx;
			font-weight: bold;
			color: #666;
		}

		.favorite-btn {
			display: flex;
			align-items: center;
			font-size: 34rpx;
			color: #999;
			padding: 6rpx 12rpx;
			border: 1rpx solid #eee;
			border-radius: 20rpx;

			.u-icon {
				margin-right: 5rpx;
			}
		}
	}

	.question-type {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 20rpx;
	}

	.question-content {
		font-size: 30rpx;
		color: #333;
		line-height: 1.6;
		margin-bottom: 40rpx;
	}

	.options-list {
		margin-bottom: 40rpx;
	}

	.option-item {
		background-color: #fff;
		border-radius: 8rpx;
		padding: 25rpx 20rpx;
		margin-bottom: 20rpx;
		border: 1rpx solid #eee;
		display: flex;
		align-items: center;

		&.selected {
			border-color: #2979ff;
			background-color: rgba(41, 121, 255, 0.1);
		}

		&.correct {
			border-color: #07C160;
			background-color: rgba(7, 193, 96, 0.1);
		}

		&.wrong {
			border-color: #FF4D4F;
			background-color: rgba(255, 77, 79, 0.1);
		}

		.option-label {
			width: 40rpx;
			height: 40rpx;
			border-radius: 50%;
			background-color: #f5f5f5;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 20rpx;
			font-size: 24rpx;
			color: #666;
		}

		&.selected .option-label {
			background-color: #2979ff;
			color: #fff;
		}

		&.correct .option-label {
			background-color: #07C160;
			color: #fff;
		}

		&.wrong .option-label {
			background-color: #FF4D4F;
			color: #fff;
		}

		.option-text {
			flex: 1;
			font-size: 28rpx;
			color: #333;
		}
	}

	.answer-analysis {
		background-color: #fff;
		border-radius: 8rpx;
		padding: 25rpx;
		margin-bottom: 30rpx;
		border-left: 4rpx solid #03B8CD;

		.analysis-title {
			font-size: 26rpx;
			color: #03B8CD;
			font-weight: bold;
			margin-bottom: 15rpx;
		}

		.analysis-content {
			font-size: 26rpx;
			color: #666;
			line-height: 1.6;
		}
	}
	
	// 判断题
	.judge-options {
	  display: flex;
	  justify-content: space-around;
	  margin-bottom: 40rpx;
	}
	
	.judge-option {
	  padding: 20rpx 60rpx;
	  border: 1rpx solid #eee;
	  border-radius: 10rpx;
	  
	  &.selected {
	    background-color: #f0f7ff;
	    border-color: #2979ff;
	  }
	  
	  &.correct {
	    background-color: #e1f3d8;
	    border-color: #67c23a;
	  }
	  
	  &.wrong {
	    background-color: #fde2e2;
	    border-color: #f56c6c;
	  }
	}
	
	// 简答题：
	.answer-input {
	  margin-bottom: 40rpx;
	}

	// 底部按钮
	.action-bar {
		position: fixed;
		bottom: 40rpx;
		left: 50%;
		height: 100rpx;
		width: 350px;
		border-radius: 30px;
		background-color: #F1F7F7;
		transform: translateX(-50%);
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.15);
		// box-shadow: 0 -2rpx 8rpx #54e6fc;

		.action-btn {
			flex: 1;
			text-align: center;
			font-size: 30rpx;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;

		}

		.prev-btn {
			color: #03B8CD;
			border-radius: 56rpx 56rpx 56rpx 56rpx;
			border: 2rpx solid #03B8CD;

		}

		.action-center {
			margin: 0 30rpx;
		}

		.action-order {
			text-align: center;
		}

		.catalog-btn {
			color: #03B8CD;
			font-weight: bold;
			border-left: 1rpx solid #eee;
			border-right: 1rpx solid #eee;
		}

		.next-btn {
			color: #03B8CD;
			font-weight: bold;
			border-radius: 56rpx 56rpx 56rpx 56rpx;
			border: 2rpx solid #03B8CD;

			&.disabled {
				color: #ffffff;
				background-color: #03B8CD;
				border-radius: 56rpx 56rpx 56rpx 56rpx;
				border: 2rpx solid #03B8CD;
			}
		}
	}

	.catalog-popup {
		padding: 30rpx;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;

			.popup-title {
				font-size: 32rpx;
				font-weight: bold;
			}

			.u-icon {
				padding: 10rpx;
			}
		}

		.question-list {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;

			.question-item {
				width: 80rpx;
				height: 80rpx;
				border-radius: 8rpx;
				background-color: #f5f5f5;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;

				&.active {
					background-color: #2979ff;
					color: #fff;
				}
				&.selected {
				  background-color: #2979ff;
				  border-color: #2979ff;
					color: #fff;
				}
				
				
				&.correct {
					background-color: #e1f3d8;
					border-color: #67c23a;
				}
				
				&.wrong {
					background-color: #fde2e2;
					border-color: #f56c6c;
				}
			}
		}
	}
</style>